package ru.spb.osll.myfit.server.execute;

import ru.spb.osll.myfit.common.ProgressCounts;
import ru.spb.osll.myfit.util.FileHelper;

import java.io.*;

public class PageWriter {
	private String head;
	private final String tail = new String( "  </BODY>\n"
					+ "</HTML>\n");
	private String m_pageName;

	public PageWriter(String pageName, String src)
		throws FileNotFoundException, IOException {
		m_pageName = pageName;
		(new FileHelper()).copyDir(src,
		              (new File(pageName)).getParent() +
		                                  File.separator + "files");
	}

	public void writeStream(ByteArrayOutputStream outputStream,
                            ProgressCounts progressCounts) {
		String strPage = outputStream.toString();
    try {
      outputStream.close();

      try {
    	  
    	strPage = replaceSomeSubstrings(strPage);
        FileOutputStream out = new FileOutputStream(m_pageName);
        try {
          OutputStreamWriter outwriter = new OutputStreamWriter(out, "windows-1251");
          PrintWriter writer = new PrintWriter(outwriter);
          setHead(progressCounts);
          writer.write(head);
          writer.write(strPage);
          writer.write(tail);
          writer.close();
          outwriter.close();
          out.close();

        } catch (UnsupportedEncodingException e) {
          out.close();
        }
      } catch (FileNotFoundException e) {

      }

    } catch (IOException e) {
    }

	}

    private void setHead (ProgressCounts progressCounts) {
      head = new String( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n"
		+ "   \"http://www.w3.org/TR/html4/strict.dtd\">\n"
		+ "<HTML>\n"
		+ "  <HEAD>\n"
        + "    <title> processed: " + progressCounts.getProgressSegments()
                  + ", right: " + progressCounts.getRight()
                  + ", wrong: " + progressCounts.getWrong()
                  + ", ignored: " + progressCounts.getIgnores()
                  + ", exceptions: " + progressCounts.getExceptions()
        + "    </title>\n"
		+ "    <LINK href=\"files" + File.separator + "css" + File.separator +
				  "fitnesse_base.css\" rel=\"stylesheet\" type=\"text/css\">\n"
		+ "    <SCRIPT src=\"files" + File.separator + "javascript"
                  + File.separator + "fitnesse.js\"></SCRIPT>\n"
		+ "  </HEAD>\n"
		+ "  <BODY>\n");
    }
    
    private String replaceSomeSubstrings(String src){
    	return src.replaceAll("class=\"hidden\"", "class=\"collapsable\"");
    }
}
